package com.rui.sideup.module.codegen.gen;

import com.rui.sideup.module.codegen.core.gen.AbstractGenerator;
import com.rui.sideup.module.codegen.core.gen.AbstractTableGenerator;
import com.rui.sideup.module.codegen.core.model.Column;
import com.rui.sideup.module.codegen.core.utils.ConfigUtils;
import com.rui.sideup.module.codegen.gen.filter.CommonFieldFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
public class JavaBeanGen extends AbstractTableGenerator {

    @Autowired
    private CommonFieldFilter filter;

    @Override
    protected Map<String, Object> getDataModel() {
        Map<String, Object> data = super.getDataModel();
        List<Column> cols = new ArrayList<>(table.getColumns());
        data.put("imports", getImports(cols));
        data.put("cols", cols);

        return data;
    }

    @Override
    public String getFileName() {
        return table.getClazzName() + ".java";
    }

    @Override
    public String getType() {
        return AbstractGenerator.MODEL;
    }

    @PostConstruct
    public void init() {
        if (filter != null && ConfigUtils.getCommonFieldFilter()) {
            this.addFilter(filter);
        }
    }

    public static List<String> getImports(List<Column> colums) {
        List<String> imports = new ArrayList<>();
        for (Column col : colums) {
            String javaTypeName = col.getJavaType().getName();
            if (!javaTypeName.startsWith("java.lang") && !imports.contains(javaTypeName)) {
                imports.add(javaTypeName);
            }
        }
        Collections.sort(imports, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        return imports;
    }

}
